package org.alwayssuper;

import org.alwayssuper.protocol.GBT32960Beans;
import org.alwayssuper.protostar.util.Explain;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import org.alwayssuper.protocol.basics.GBTMessage;
import org.alwayssuper.protocol.codec.GBTMessageAdapter;

/**
 * GBT32960协议解码分析工具
 * 仿照JT808协议的Elucidator实现
 * 用于分析和测试GBT32960协议的编码解码功能
 * @author alwaysSuper
 * https://gitee.com/alwayssuper/gbt32960-server
 */
public class Elucidator extends GBT32960Beans {

    public static final GBTMessageAdapter coder = new GBTMessageAdapter("org.alwayssuper.protocol");

    public static void main(String[] args) {
        // 测试2025版本实时上报数据
        String hex = "242401FE4C46504832413142304B3141313233343501009719081F0E1E00000138393836303132333435363738393031323334350202035041434B30303030313233343536373839303132333435365041434B30303030323334353637383930313233343536375041434B30303030333435363738393031323334353637385041434B30303030343536373839303132333435363738395041434B303030303536373839303132333435363738393043";
        GBTMessage msg = H2025(G01_2025());

        msg = decode(hex);
        hex = encode(msg);
    }

    /**
     * 编码GBT消息
     * @param message GBT消息对象
     * @return 十六进制字符串
     */
    private static String encode(GBTMessage message) {
        System.out.println("==================== 编码分析 ====================\n");
        Explain explain = new Explain();
        ByteBuf buf = null;
        String hex = null;
        
        try {
            buf = coder.encode(message, explain);
            hex = ByteBufUtil.hexDump(buf).toUpperCase();
            
            System.out.println("消息对象: " + message);
            System.out.println("编码结果: " + hex);
            System.out.println("字节长度: " + buf.readableBytes());
            explain.println();
            
        } catch (Exception e) {
            System.err.println("编码失败: " + e.getMessage());
            e.printStackTrace();
        } finally {
            if (buf != null) {
                buf.release();
            }
        }
        
        return hex;
    }

    /**
     * 解码GBT消息
     * @param hex 十六进制字符串
     * @return GBT消息对象
     */
    private static GBTMessage decode(String hex) {
        System.out.println("==================== 解码分析 ====================\n");
        Explain explain = new Explain();
        GBTMessage message = null;
        
        try {
            ByteBuf buf = Unpooled.wrappedBuffer(ByteBufUtil.decodeHexDump(hex));
            message = coder.decode(buf, explain);
            
            System.out.println("输入报文: " + hex);
            System.out.println("字节长度: " + (hex.length() / 2));
            System.out.println("解码结果: " + message);
            explain.println();
            
        } catch (Exception e) {
            System.err.println("解码失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        return message;
    }


}